package de.sbi.AHLib;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

import com.google.gson.Gson;

import de.sbi.AHLibjson.AuctionsContainer;
import de.sbi.AHLibjson.Files;
import de.sbi.AHLibjson.FilesContainer;

/**
 * 
 * @author sb
 * 
 */
public class DataFetcher {

	String url;

	int lastModified;

	String realm;

	String region;

	private Gson gson = new Gson();

	public static final String URL_US = "us.battle.net";

	public static final String URL_EU = "eu.battle.net";

	public DataFetcher(String realm, String region) {
		this.realm = realm;
		this.region = region;
	}

	public AuctionsContainer fetchData() {

		AuctionsContainer auctionsContainer = null;

		try {
			// TODO: File-Caching ("lastModified") + gzip Handling (possible?)
			URL filesURL = getURL();

			String sfilesContainer = getFile(filesURL);

			FilesContainer filesContainer = gson.fromJson(sfilesContainer,
					FilesContainer.class);

			Files mainFile = filesContainer.getMain();

			URL auctionURL = new URL(mainFile.getUrl());

			String sAuctionsContainer = getFile(auctionURL);

			auctionsContainer = gson.fromJson(sAuctionsContainer,
					AuctionsContainer.class);
		} catch (IOException ex) {
			ex.printStackTrace();
		}

		return auctionsContainer;
	}

	protected URL getURL() {
		String host = null;

		URL intURL = null;

		if (this.region == null || this.region.equals("EU")) {
			host = "http://" + URL_EU;
		} else {
			host = "http://" + URL_US;
		}
		try {
			intURL = new URL(host + "/api/wow/auction/data/" + this.realm);

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return intURL;
	}

	protected String getFile(URL url) throws IOException {
		URLConnection fc = url.openConnection();

		InputStreamReader isr = new InputStreamReader(fc.getInputStream());

		BufferedReader in = new BufferedReader(isr);
		String inputLine;

		StringBuffer inSb = new StringBuffer();

		while ((inputLine = in.readLine()) != null) {
			inSb.append(inputLine);
		}
		in.close();

		return inSb.toString();
	}

}
